package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderSettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 当月预约信息展示
     * @param year
     * @param month
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(Integer year,Integer month){
        log.info("当月预约信息展示:年{},月:{}",year,month);
        List<OrderSetting> orderSettings = orderSettingService.getOrderSettingByMonth(year,month);

        List<Map<String,Object>> mapList = new ArrayList<>();
        for (OrderSetting orderSetting : orderSettings) {
        //创建用于日期处理的工具类Calendar对象
            Calendar calendar = Calendar.getInstance();
        //设置时间为预约日期
            calendar.setTime(orderSetting.getOrderDate());
            Map<String,Object> map = new HashMap<>();
        //设置日期限-当月第几天
            map.put("date",calendar.get(Calendar.DAY_OF_MONTH));
        //设置数量-当天允许的预约数量
            map.put("number",orderSetting.getNumber());
        //设置已经预约的人数
            map.put("reservations",orderSetting.getReservations());

            mapList.add(map);
        }
        return new Result(true, MessageConst.ACTION_SUCCESS,mapList);
    }

    /**
     * 可预约单独设置
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting ordersetting){
        log.info("可预约单独设置：{}",ordersetting);
        //查询当前有无安排
        orderSettingService.editNumberByDate(ordersetting.getOrderDate(),ordersetting.getNumber());
        return new Result(true,MessageConst.ORDERSETTING_SUCCESS);
    }


    /**
     * 通过excel导入数据
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile file){
        log.info("execl导入数据:{}",file);
        //获取源文件名
        String fileName = file.getOriginalFilename();
        Workbook workbook = null;
        if (fileName.endsWith(".xlsx")){
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //遍历数据
        List<OrderSetting> orderSettings = new ArrayList<>();
        for (Sheet sheet : workbook) {
            //第一行为表头从第二行开始读取数据
            for (int i = 1; i < sheet.getLastRowNum(); i++) {
             //获取每一行
                Row row = sheet.getRow(i);
                //解析行
               OrderSetting orderSetting =  parseOrderSetting(row);
               orderSettings.add(orderSetting);
            }
        }
        //批量插入数据
        orderSettingService.addAll(orderSettings);

        return new Result(true,MessageConst.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 从excel行提取OrderSetting数据
     * @param row
     * @return
     */
    private OrderSetting parseOrderSetting(Row row) {
        Date date = null;
        Integer number =  null;
        //获取日期的数据
        if(row.getCell(0)!=null){
             date = row.getCell(0).getDateCellValue();
        }
        //获取最大预约数
        if(row.getCell(1)!=null){
            number = (int) row.getCell(1).getNumericCellValue();
        }
        // 判断是否缺少数据
        if(null == date || null == number){
            throw new BusinessRuntimeException(String.format("缺少必填数据,%s 第%d行",row.getSheet().getSheetName(),row.getRowNum()+1));
        }  // 判断是否缺少数据
        return  new OrderSetting(date,number);
    }
}
